import { Constructor } from "../project";
import * as mysql from "mysql";
import {config} from '../config';


interface ITable{
	tableName:string;
}

function Table(tableName:string){
	return function(target:Constructor):any{
		target.prototype.tableName=tableName;
		return class extends target implements ITable{
			public tableName:string=tableName;
		}
	}
}

class DBHelper{
	private connection:mysql.Connection;
	constructor(){
		this.connection=mysql.createConnection(config);
	}
	public query<T>(sql:string,param:any[]):Promise<T>{
		return new Promise((resolve, reject) => {
			this.connection.connect();
			this.connection.query(sql,param,(err,results)=>{
				if(err) reject(err);
				resolve(results);
			})
		});
	}
}


class A{
	public aa:string='123';
}

function Inject(InjectClass:Constructor){
	return function(target:any,key:string):any{
		let OldValue = target[key];
		let value = new InjectClass();
		Object.defineProperty(target,key,{
			get(){
				return value;
			},
			set(){
				console.log('注入之后就不能再设置！');
				return;
			}
		})
	}
}

function Param(target:any,key:string,index:number){

	console.log(target[key])
}
function insert(flieds:string){
	return function(target:any,key:string,descriptor:PropertyDescriptor){
		let oldval = descriptor.value;
		descriptor.value=async function(){
			let paramsStirng = flieds.split(',').map(()=>'?').join(',');
			const sql = `insert into ${target.tableName}(${flieds}) values (${paramsStirng});`;
			const truevalue = Array.from(arguments);
			let results;
			try {
				results=await new DBHelper().query(sql,truevalue);
			} catch (error) {
				console.log(error);
			}
			return results;
		}
		return descriptor;
	}
}
@Table("user")
class User{
	@insert("uname,pwd")
	aaa(username:string,password:string){}


	bbb(){}
}


new User().aaa("宋姗姗","hahah");